/*
 * @Date: 2022-02-14 10:46:28
 * @LastEditors: 春贰
 * @Desc:
 * @LastEditTime: 2023-11-28 11:46:07
 * @FilePath: \server\system\router\InitRouter.go
 */

package router

import (
	"fmt"
	//"io/fs"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/unrolled/secure" 
	"go-easy-dashboard/system/core/config"
	"go-easy-dashboard/system/middleware"
	"go-easy-dashboard/system/util/sys" 
)

func InitRouter() *gin.Engine {

	basedir := sys.ExecutePath() + "\\" //根目录
	r := gin.New()

	r.Use(middleware.CorsMid())
	r.MaxMultipartMemory = int64(config.Instance().Upload.MaxSize * 1024 * 1024 * 2)
	r.Static("/runtime/file", basedir+"runtime/file")
	//r.StaticFile("/favicon.ico", "./resources/favicon.ico")
	r.GET("/", func(c *gin.Context) {
		c.Request.URL.Path = "/html"
		r.HandleContext(c)
	})
	r.Static("/html", basedir+"html")     //静态文件
	r.Static("/mobile", basedir+"mobile") //静态文件

	r.Static("/static", basedir+"custom/static") //静态文件

	// fads, _ := fs.Sub(staticFs, "static")
	// r.StaticFS("/static", http.FS(fads))                                               //挂载到二进制中

	r.StaticFS("/apidoc", http.Dir(basedir+"apidoc"))
	r.StaticFS("/upload", http.Dir(basedir+"custom/"+config.Instance().Upload.Path)) //挂载目录提供http访问
	//ebr里的静态文件
	r.StaticFS("/ebr", http.Dir(basedir+"custom/ebr"))

	//r.Use(gin.Logger())
	//r.Use(gin.Recovery())

	//注册基础路由
	RegisterRouter(r)
	//全局中间件是否开启https端口转发
	if config.Instance().App.HttpsPort != 0 {
		r.Use(TlsHandler())
	}
	return r
}

func TlsHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		secureMiddleware := secure.New(secure.Options{
			SSLRedirect: true,
			SSLHost:     fmt.Sprintf(":%d", config.Instance().App.HttpsPort),
		})
		err := secureMiddleware.Process(c.Writer, c.Request)
		if err != nil {
			return
		}
		c.Next()
	}
}
